<template>
  <div class="app-container">

    <el-container direction="horizontal" style="border-bottom: deepskyblue solid 1px">
      <el-header>
        <el-form :model="formData" size="medium" label-width="100px" inline>
          <el-form-item label="设置评价名称" prop="evaluationName">
            <el-input id="v-step-1" v-model="formData.evaluationName" placeholder="请输入此次评价名称" clearable style="width: 240px"></el-input>
          </el-form-item>
          <el-form-item id="v-step-2" label="选择评价方式">
            <el-select v-model="evaluationMethodId" placeholder="请选择评价方式" clearable style="width: 240px">
              <el-option v-for="item in wayOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-Refresh" size="mini" @click="handleRecord">操作记录</el-button>
            <el-button type="primary" icon="el-icon-Refresh" size="mini" @click="showTour">页内操作指引</el-button>
            <el-button id="v-step-7" type="primary" icon="el-icon-Refresh" size="mini" @click="toResult">查看评估结果</el-button>
          </el-form-item>
        </el-form>
      </el-header>
    </el-container>

    <el-container direction="horizontal" style="border-bottom: deepskyblue solid 1px; height: 80%">
      <el-main width="50%" >
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="标准号" prop="standardCode">
            <el-input
              v-model="queryParams.standardCode"
              placeholder="请输入标准号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table
          id="v-step-3"
          v-loading="standloading"
          :data="excelList"
          @selection-change="handleSelectionChange"
          height="84%"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" align="center" prop="id" />
          <el-table-column label="标准号" align="center" prop="standardCode" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                id="v-step-4"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleLook(scope.row)"
              >查看指标原始数据</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div>总条目数: {{ excelList.length }}</div>

        <!-- 添加或修改excel(标准三级指标)对话框 -->
        <el-dialog :visible.sync="standOpen" width="800px" append-to-body>
          <el-table :data="tableData">
            <el-table-column label="指标名称" prop="label"></el-table-column>
            <el-table-column label="数值" prop="value"></el-table-column>
          </el-table>
          <div slot="footer" class="dialog-footer">
            <el-button @click="closeStand">关闭</el-button>
          </div>
        </el-dialog>
      </el-main>
      <el-main width="50%" >
        <el-form :model="SystemqueryParams" ref="SystemqueryForm" size="small" :inline="true" v-show="SystemshowSearch" label-width="68px">
          <el-form-item label="体系名称" prop="systemName">
            <el-input
              v-model="SystemqueryParams.systemName"
              placeholder="请输入体系名称"
              clearable
              @keyup.enter.native="SystemhandleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="SystemhandleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="SystemresetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table id="v-step-5" height="84%" v-loading="loading" :data="systemList" @selection-change="SystemhandleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <!--          <el-table-column label="体系id" align="center" prop="id" />-->
          <el-table-column label="体系名称" align="center" prop="systemName" />
          <!--          <el-table-column label="修改时间" align="center" prop="modifyTime" width="180">-->
          <!--            <template slot-scope="scope">-->
          <!--              <span>{{ parseTime(scope.row.modifyTime, '{y}-{m}-{d}') }}</span>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-search"
                @click="handleView(scope.row)"
              >查看</el-button>
              <!--              <el-button-->
              <!--                size="mini"-->
              <!--                type="text"-->
              <!--                icon="el-icon-edit"-->
              <!--                @click="handleMatrix(scope.row), judgeDialogOpen=true"-->
              <!--                v-hasPermi="['system:tree:edit']"-->
              <!--              >专家评分</el-button>-->
            </template>
          </el-table-column>
        </el-table>
        <div>总条目数: {{ systemList.length }}</div>
        <!--          <pagination-->
        <!--            v-show="total>0"-->
        <!--            :total="total"-->
        <!--            :page.sync="SystemqueryParams.pageNum"-->
        <!--            :limit.sync="SystemqueryParams.pageSize"-->
        <!--            @pagination="SystemgetList"-->
        <!--          />-->
      </el-main>
      <el-dialog :visible.sync="treeOpen"  >
        <el-tree
          :data="treeData"
          node-key="id"
          :expand-on-click-node="false"
          default-expand-all
          style="overflow:scroll; max-height: 300px; min-height: 300px"
        >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ data.indicatorName }}</span>

          <!--          <span>{{ data.subjectiveWeight }}</span>-->
        </span>
        </el-tree>
      </el-dialog>

    </el-container>
    <el-container style="margin-top: 10px">
      <el-footer style="text-align: center" >
        <el-button :disabled="isEvaluating" id="v-step-6" round type="primary" icon="el-icon-document" size="medium" @click="startEvaluating" >开始评价</el-button>
      </el-footer>
    </el-container>



    <!--    <div class="EvaluateRecord">-->
    <!--      -->
    <!--    </div>-->
    <!--    <div class="SystemTable">-->

    <!--    </div>-->
    <!--    <div class="StandList">-->

    <!--    </div>-->
    <!--    <div class="startButton">-->
    <!--      -->
    <!--    </div>-->
    <v-tour name="myTour" :steps="steps" :options="myOptions" :callbacks="myCallbacks"></v-tour>

    <NotificationBox ref="notificationBox"></NotificationBox>
  </div>

</template>

<script>
// import { listSystem } from "@/api/indicator/system";
// import { listExcel, getExcel, delExcel, addExcel, updateExcel } from "@/api/system/excel";
import { startEvaluate ,listExcel ,listSystem} from "@/api/evaluate/startEvaluate.js"
import NotificationBox from '@/components/NotificationBox';
import {getIndicatorsBySystemId} from "@/api/indicator/indicator";
import {listModelMethod} from "@/api/modelMethod/modelMethod";


const labelMap = {
  a11: "A11(参与国家影响力)",
  a12: "A12(参与企业/组织影响力)",
  a13: "A13(起草人员)",
  b11: "B11(标准转化)",
  b12: "B12(其他标准引用)",
  b13: "B13(被法律法规引用)",
  b14: "B14(其他工程应用)",
  b21: "B21(标准传播)",
  b22: "B22(认证认可)",
  b23: "B23(标准关注度)",
  b24: "B24(标准衍生材料传播)",
  b31: "B31(标准引领性)",
  b32: "B32(标准创新性)",
  b33: "B33(标准获奖)",
  b41: "B41(社会关注度)",
  b42: "B42(可持续发展支撑度)",
  b43: "B43(对外贸易应用(国际贸易影响))",
  b44: "B44(产业扩散广度)"
};
export default {
  components: {
    NotificationBox
  },
  name: "access/start",
  data() {
    return {
      isEvaluating: false, // 初始化为 false
      hasCompletedTour: false,
      myOptions: {
        useKeyboardNavigation: false,
        labels: {
          buttonSkip: '跳过',
          buttonPrevious: '上一步',
          buttonNext: '下一步',
          buttonStop: '完成'
        }
      },
      steps: [
        {
          target: '#v-step-1',  // We're using document.querySelector() under the hood
          header: {
            title: '第一步',
          },
          content: `设置此次评估名称!`
        },
        {
          target: '#v-step-2',
          header: {
            title: '第二步',
          },
          params: {
            placement: 'left' // Any valid Popper.js placement. See https://popper.js.org/popper-documentation.html#Popper.placements
          },
          content: '选择评估方法'
        },
        {
          target: '#v-step-3',
          header: {
            title: '第三步',
          },
          content: `选择评价的标准!<br>若无标准，请在数据管理中上传标准数据.`,
          params: {
            placement: 'left' // Any valid Popper.js placement. See https://popper.js.org/popper-documentation.html#Popper.placements
          }
        },

        {
          target: '#v-step-4',
          header: {
            title: '第四步',
          },
          content: `查看标准的指标数据!<br>确认数据是否完备`,
          params: {
            placement: 'right' // Any valid Popper.js placement. See https://popper.js.org/popper-documentation.html#Popper.placements
          }
        },
        {
          target: '#v-step-5',
          header: {
            title: '第五步',
          },
          content: `选择一个指标体系!<br>也可以在指标体系菜单新建指标体系.`,
          params: {
            placement: 'right' // Any valid Popper.js placement. See https://popper.js.org/popper-documentation.html#Popper.placements
          }
        },
        {
          target: '#v-step-6',
          header: {
            title: '第六步',
          },
          content: '点击开始进行评价',
          params: {
            placement: 'top' // Any valid Popper.js placement. See https://popper.js.org/popper-documentation.html#Popper.placements
          }
        },
        {
          target: '#v-step-7',
          header: {
            title: '第七步',
          },
          content: '当评估完成，点击查看结果',
          params: {
            placement: 'right' // Any valid Popper.js placement. See https://popper.js.org/popper-documentation.html#Popper.placements
          }
        }
      ],
      myCallbacks: {
        onSkip: this.usedTour,
        onFinish: this.usedTour
      },
      fullscreenLoading: false,
      tableData :[],
      labelMap,
      formData: {
        evaluationName: undefined,
      },
      evaluationMethodId: undefined,
      rules: {
        EvaluateName: [],
        evaluationMethodName: undefined
      },
      startSendForm: {
        systemId: undefined,
        standardCodes: [],
        evaluationMethodId: undefined,
        evaluationName: undefined,
        evaluationMethodName: undefined,
        systemName: undefined,
      },
      // 遮罩层
      loading: true,
      standloading: true,
      // 选中数组
      Systemids: [],
      SystemNames:[],
      // 非单个禁用
      single: true,
      standsingle: true,
      // 显示搜索条件
      SystemshowSearch: true,
      // 非多个禁用
      multiple: true,
      standmultiple: true,
      systemList: [],
      // excel(标准三级指标)表格数据
      excelList: [],
      excelshowList:{},
      // 指标体系查询参数
      SystemqueryParams: {
        pageNum: 1,
        pageSize: 10,
        systemName: null,
        description: null,
        createUser: null,
        modifyUser: null,
        modifyTime: null
      },
      //选择评估方式
      wayOptions : [],
      //标准表相关
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      standtotal:0,

      // 是否显示弹出层
      open: false,
      standOpen: false,
      treeOpen:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        standardCode: null,
      },
      currentIndicatorSystem: {
        id: null,
        systemName: null,
        children: []
      },
      treeData: [],
    };
  },
  created() {
    this.getList();
    this.SystemgetList();
    this.getModelMethodList();
  },
  mounted: function () {
    console.log("是否以前访问过"+this.hasCompletedTour);
    //读取localStorage中存储的是否访问过的信息则为true
    this.hasCompletedTour = localStorage.getItem('hasCompletedTour') === 'true';
    console.log(this.hasCompletedTour);
    if(!this.hasCompletedTour) {
      this.$tours['myTour'].start()
    }
  },
  methods: {
    //标记已经使用过导航
    usedTour()
    {
      //访问结束，保存到localstorage为true
      localStorage.setItem('hasCompletedTour', true);
      console.log("已经使用过了"+this.hasCompletedTour);
    },
    showTour() {
      this.setupTourSteps();
      this.$tours['myTour'].start()
    },
    setupTourSteps() {
      if(this.excelList.length==0) {
        // 假设我们有一个步骤，它依赖于表格中的第一个元素
        this.steps=  [
          {
            target: '#v-step-1',  // We're using document.querySelector() under the hood
            header: {
              title: '第一步',
            },
            content: `设置此次评估名称!`
          },
          {
            target: '#v-step-2',
            header: {
              title: '第二步',
            },
            params: {
              placement: 'left' // Any valid Popper.js placement. See https://popper.js.org/popper-documentation.html#Popper.placements
            },
            content: '选择评估方法'
          },
          {
            target: '#v-step-3',
            header: {
              title: '第三步',
            },
            content: `选择评价的标准!<br>若无标准，请在数据管理中上传标准数据.`,
            params: {
              placement: 'left' // Any valid Popper.js placement. See https://popper.js.org/popper-documentation.html#Popper.placements
            }
          },
          {
            target: '#v-step-5',
            header: {
              title: '第四步',
            },
            content: `选择一个指标体系!<br>也可以在指标体系菜单新建指标体系.`,
            params: {
              placement: 'right' // Any valid Popper.js placement. See https://popper.js.org/popper-documentation.html#Popper.placements
            }
          },
          {
            target: '#v-step-6',
            header: {
              title: '第五步',
            },
            content: '点击开始进行评价',
            params: {
              placement: 'top' // Any valid Popper.js placement. See https://popper.js.org/popper-documentation.html#Popper.placements
            }
          },
          {
            target: '#v-step-7',
            header: {
              title: '第六步',
            },
            content: '当评估完成，点击查看结果',
            params: {
              placement: 'right' // Any valid Popper.js placement. See https://popper.js.org/popper-documentation.html#Popper.placements
            }
          }
        ];
      }
    },
    toResult(){
      this.$router.push('/access/result/list')
    },
    /** 查询【请填写功能名称】列表 */
    SystemgetList() {
      this.loading = true;
      listSystem(this.SystemqueryParams).then(response => {
        this.systemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getModelMethodList() {
      this.wayOptions = [];
      listModelMethod().then(response => {
        this.modelMethodList = response.rows;
        console.log(this.modelMethodList);
        //遍历modelMethodList
        for(let i=0;i<this.modelMethodList.length;i++){
          this.wayOptions.push({
            value: this.modelMethodList[i].id,
            label: this.modelMethodList[i].evaluationMethod
          })
        }
      });
    },
    getList() {
      this.standloading = true;
      listExcel(this.queryParams).then(response => {
        this.excelList = response.rows;
        this.standtotal = response.total;
        this.standloading = false;
      });
    },
    /** 搜索按钮操作 */
    SystemhandleQuery() {
      this.SystemqueryParams.pageNum = 1;
      this.SystemgetList();
    },
    /** 重置按钮操作 */
    SystemresetQuery() {
      this.resetForm("SystemqueryForm");
      this.SystemhandleQuery();
    },
    // 多选框选中数据
    SystemhandleSelectionChange(selection) {
      this.Systemids = selection.map(item => item.id)
      this.SystemNames=selection.map(item => item.systemName)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    subscribeToSSE() {
      this.eventSource = new EventSource('http://localhost:8181/sse/subscribe');

      this.eventSource.onopen = () => {
        console.log("SSE: 连接已建立");
      };

      this.eventSource.onmessage = (event) => {
        console.log('SSE: 收到消息: ', event.data);
        this.$message.success(event.data);

        // 收到消息后关闭连接
        this.eventSource.close();
        this.eventSource = null;
      };

      this.eventSource.onerror = (error) => {
        console.error('SSE: 连接有误,', error);
        this.$message.warning("SSE 订阅失败，请联系管理员");
        this.eventSource.close();
        this.eventSource = null;
      };
    },
    async startEvaluating() {
      try {
        // 验证表单
        if (this.Systemids.length === 0) {
          this.$modal.msgWarning("请选择评估体系");
          return;
        }
        if (this.Systemids.length > 1) {
          this.$modal.msgWarning("请选择一个评估体系");
          return;
        }
        if (!this.formData.evaluationName) {
          this.$modal.msgWarning("请输入此次评价名称");
          return;
        }
        if (!this.evaluationMethodId) {
          this.$modal.msgWarning("请选择评估方式");
          return;
        }
        if (this.ids.length === 0) {
          this.$modal.msgWarning("请选择评价标准");
          return;
        }

        // 准备数据
        this.startSendForm = {
          systemId: this.Systemids[0],
          systemName: this.SystemNames[0],
          standardCodes: this.ids,
          evaluationMethodId: this.evaluationMethodId,
          evaluationName: this.formData.evaluationName,
          evaluationMethodName: this.wayOptions.find(option => option.value === this.evaluationMethodId)?.label || ''
        };

        // 开始评估
        this.subscribeToSSE();
        this.isEvaluating = true;
        this.$refs.notificationBox.show('正在评估中...,请稍后查看');

        const response = await startEvaluate(this.startSendForm);
        if (response.code === 200) {
          this.$refs.notificationBox.show('评估已开始，请稍后查看结果');
        } else {
          this.$refs.notificationBox.show('评价失败');
        }
      } catch (error) {
        console.error('评估过程中发生错误:', error);
        this.$refs.notificationBox.show('评估过程中发生错误');
      } finally {
        setTimeout(() => {
          this.isEvaluating = false;
          this.$refs.notificationBox.hide();
        }, 2000);
      }
    },
    // 打开弹出层
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.standardCode)
      this.standsingle = selection.length!==1
      this.standmultiple = !selection.length
      console.log(this.ids)
    },
    handleRecord(){
      this.$router.push('/access/record')
    },
    closeStand(){
      this.excelshowList ={}
      this.tableData=[]
      this.standOpen = false;
    },
    handleLook(row){
      console.log(row)
      this.excelshowList=row
      this.tableData=[]
      for (let key in this.excelshowList) {
        let label = labelMap[key] || key; // 使用映射表或默认显示键名
        this.tableData.push({label: label, value: this.excelshowList[key]}); // 存入数组中
        this.tableData=this.tableData.filter(item => item.label !== 'id');
        this.tableData=this.tableData.filter(item => item.label !== 'standardCode');
        this.tableData=this.tableData.filter(item => item.label !== 'createBy');
        this.tableData=this.tableData.filter(item => item.label !== 'createTime');
        this.tableData=this.tableData.filter(item => item.label !== 'updateBy');
        this.tableData=this.tableData.filter(item => item.label !== 'remark');
        this.tableData=this.tableData.filter(item => item.label !== 'updateTime');
      }
      this.standOpen = true;
    },
    /** 点击查看 */
    handleView(row){
      // this.currentIndicatorSystem={
      //   id: null,
      //   systemName: null,
      //   children: []}
      getIndicatorsBySystemId(row.id).then(response => {
        this.currentIndicatorSystem.systemName = row.systemName;
        this.currentIndicatorSystem.id = row.id;
        this.currentIndicatorSystem.children = response.rows;
        console.log(this.currentIndicatorSystem)
        this.treeData = this.currentIndicatorSystem.children;
        console.log(this.treeData)
        this.treeOpen=true;
      });
    },
  }
};
</script>

<style scoped>
.app-container{
  position: absolute;
  height: 100%;
  width: 100%;
}
.EvaluateName{
  position: absolute;
  left: 0;
  width: 33% !important;
  height: 15% !important;
  margin: 1% 3%;

}
.EvaluateRecord{
  position: absolute;
  right: 40%;
  width: 33% !important;
  height: 15% !important;
  margin: 1% 3%;
}
.EvaluateMethod{
  position: absolute;
  top:10%;
  left: 0;
  width: 33% !important;
  height: 15% !important;
  margin: 1% 3%;
}
.SystemTable{
  position: absolute;
  bottom: 10%;
  left: 0;
  /*text-align: center;*/
  width: 48% !important;
  height: 70% !important;
  margin-top: 1%;
  margin-right: 4%;
  margin-left: 1%;
}
.StandList{
  position: absolute;
  right: 0;
  bottom: 10%;
  /*text-align: center;*/
  width: 48% !important;
  height: 70% !important;
  margin-top: 1% ;
  margin-left: 4%;
  margin-right: 1%;
}
.startButton{
  position: absolute;
  width: 100%;
  bottom: 8%;
  text-align: center;

}
.startButton .el-button{
  width: 160px;
  height: 40px;
  font-size: 1rem;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

</style>
